package com.pengpeng.advice.config;

import com.pengpeng.advice.exception.CMSException;
import com.pengpeng.advice.result.R;
import com.pengpeng.advice.result.ResultCodeEnum;
import com.pengpeng.advice.utils.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author 彭鹏
 * @date 2021/10/29.
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**-------- 通用异常处理方法 --------**/
    @ExceptionHandler(Exception.class)
    public R error(Exception e) {
        log.error(ExceptionUtil.getMessage(e));
        return R.error().message(e.getMessage()).code(-1);
    }

    /**-------- 指定异常处理方法 --------**/
    @ExceptionHandler(NullPointerException.class)
    public R error(NullPointerException e) {
        log.error(ExceptionUtil.getMessage(e));
        return R.setResult(ResultCodeEnum.NULL_POINT);
    }

    @ExceptionHandler(HttpClientErrorException.class)
    public R error(IndexOutOfBoundsException e) {
        log.error(ExceptionUtil.getMessage(e));
        return R.setResult(ResultCodeEnum.HTTP_CLIENT_ERROR);
    }
    /**-------- 自定义定异常处理方法 --------**/
    @ExceptionHandler(CMSException.class)
    public R error(CMSException e) {
        log.error(ExceptionUtil.getMessage(e));
        return R.error().message(e.getMessage()).code(e.getCode());
    }
}